package com.hainiu.cat.web.codeStudy.cas;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * create by biji.zhao on 2021/4/1
 */
public class CasCounter {
    private SimulatedCAS value;

    public int getValue() {
        return value.getValue();
    }

    public CasCounter(SimulatedCAS value) {
        this.value = value;
    }

    public int increment() {
        int oldValue = value.getValue();
        while (value.compareAndSwap(oldValue, oldValue + 1) != oldValue)
            oldValue = value.getValue();
        return oldValue + 1;
    }

    public static void main(String[] args) {
//        casIncrement();
//        atomic();

        List<String> result = Lists.newArrayList();
        CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("task1");

            result.add("task1");
            return "task1";
        });
        CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("task2");

            result.add("task2");
            return "task2";
        });
        CompletableFuture<Void> future = CompletableFuture.allOf(task1, task2);
        future.join();

        System.out.println("===========执行完毕");
        result.forEach(System.out::println);

        System.out.println("all done");

    }

    private static void atomic() {
        AtomicInteger atomicInteger = new AtomicInteger();
        atomicInteger.getAndIncrement();
        System.out.println(atomicInteger);
    }


    private static void casIncrement() {
        SimulatedCAS simulatedCAS = new SimulatedCAS();
        CasCounter casCounter = new CasCounter(simulatedCAS);
        casCounter.increment();

        System.out.println(casCounter.getValue());
    }
}
